package com.nowar.common.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.AbstractFileResolvingResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

/**
 * @Author: 谢无殇。
 * @Date : 2024-03-26 22:12
 */
public class NoWarPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    /**
     * Comment for <code>propertiesPersister</code>
     * 处理properties文件的对象
     */
    private PropertiesProcessor propertiesPersister = new PropertiesProcessor();

    private Resource[] locations;

    @Override
    public void setLocation(Resource location) {
        this.locations = new Resource[]{location};
    }

    @Override
    public void setLocations(Resource[] locations) {
        this.locations = locations;
    }

    @Override
    protected void loadProperties(Properties props) throws IOException {
        if (this.locations != null) {
            InputStream is = null;
            Reader reader = null;
            String filename = null;

            for (Resource location : this.locations) {
                is = null;
                try {
                    is = location.getInputStream();
                    reader = new InputStreamReader(is);

                    filename = (location instanceof AbstractFileResolvingResource) ? location
                            .getFilename() : null;
                    if ((filename != null) && (filename.endsWith(".xml"))) {
                        this.propertiesPersister.loadFromXml(props, is);
                    } else {
                        this.propertiesPersister.load(props, reader);
                    }
                } catch (IOException ex) {
                    System.out.println("");
                } finally {
                    if (is != null)
                        is.close();
                }
            }
        }
    }


}
